package com.dog.basics.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSObject;
import com.dd.plist.NSString;
import com.dd.plist.PropertyListParser;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @program: d_tea_machine
 *
 * @description: 读取APK丶IPA丶WGT版本号信息等
 *
 * @author: Guo
 *
 * @create: 2020-01-09 11:16
 **/
public class ReadUtil {

    /**
     * 获取APK信息
     * @param fileUrl
     * @return
     * guonh 2020年1月9日
     */
    public static AppVersionInfo readApk(String fileUrl) {
        AppVersionInfo appVersionInfo = new AppVersionInfo();
        try {
            File file = FileUtil.file(fileUrl);
            ApkFile apkFile = new ApkFile(file);
            ApkMeta apkMeta = apkFile.getApkMeta();
            appVersionInfo.setItemName(apkMeta.getName());
            appVersionInfo.setPackageName(apkMeta.getPackageName());
            appVersionInfo.setVersionNo(apkMeta.getVersionName());
            appVersionInfo.setVersionCode(StrUtil.toString(apkMeta.getVersionCode()));
        } catch (Exception e) {
            return null;
        }
        return appVersionInfo;
    }

    /**
     * 获取IOS包版本信息
     * @param fileUrl
     * @return
     * guonh 2020年1月9日
     */
    public static AppVersionInfo readIpa(String fileUrl) {
        AppVersionInfo appVersionInfo = new AppVersionInfo();
        try {
            File file = FileUtil.file(fileUrl);
            InputStream is = new FileInputStream(file);
            InputStream is2 = new FileInputStream(file);
            ZipInputStream zipIns = new ZipInputStream(is);
            ZipInputStream zipIns2 = new ZipInputStream(is2);
            ZipEntry ze;
            InputStream infoIs = null;
            NSDictionary rootDict = null;
            while ((ze = zipIns.getNextEntry()) != null) {
                if (!ze.isDirectory()) {
                    String name = ze.getName();
                    if (null != name && name.toLowerCase().contains(".app/info.plist")) {
                        ByteArrayOutputStream copy = new ByteArrayOutputStream();
                        int chunk = 0;
                        byte[] data = new byte[1024];
                        while (-1 != (chunk = zipIns.read(data))) {
                            copy.write(data, 0, chunk);
                        }
                        infoIs = new ByteArrayInputStream(copy.toByteArray());
                        rootDict = (NSDictionary) PropertyListParser.parse(infoIs);
                        break;
                    }
                }
            }
            ////////////////////////////////////////////////////////////////
            //如果想要查看有哪些key ，可以把下面注释放开
            //            for (String keyName : rootDict.allKeys()) {
            //				System.out.println(keyName + ":" + rootDict.get(keyName).toString());
            //			  }
            NSObject layName = rootDict.objectForKey("CFBundleDisplayName");
            appVersionInfo.setItemName(layName.toString());
            // 应用包名
            NSString parameters = (NSString) rootDict.get("CFBundleIdentifier");
            appVersionInfo.setPackageName(parameters.toString());
            // 应用版本名
            parameters = (NSString) rootDict.objectForKey("CFBundleShortVersionString");
            appVersionInfo.setVersionNo(parameters.toString());
            //应用版本号
            parameters = (NSString) rootDict.get("CFBundleVersion");
            appVersionInfo.setVersionCode(parameters.toString());
            /////////////////////////////////////////////////
            infoIs.close();
            is.close();
            zipIns.close();
        } catch (Exception e) {
            return null;
        }
        return appVersionInfo;

    }

    /**
     * 获取Wgt包版本信息 (说明:只能获取非原生前端的混合开发wgt在线升级包信息)
     * @param fileUrl
     * @return
     * guonh 2020年1月9日
     */
    public static AppVersionInfo readWgt(String fileUrl) {
        AppVersionInfo appVersionInfo = new AppVersionInfo();
        try {
            JarFile jar = new JarFile(fileUrl);
            ZipEntry entry = jar.getEntry("manifest.json");
            InputStream is = jar.getInputStream(entry);
            String fileContent = getContent(is);
            Map<String,String> content = JSONUtil.toBean(fileContent, HashMap.class);
            //读取获取
            appVersionInfo.setItemName(content.get("name"));
            appVersionInfo.setPackageName(content.get("id"));
            JSONObject jsonObject = new JSONObject(content.get("version"));
            appVersionInfo.setVersionNo(jsonObject.get("name")+"");
            appVersionInfo.setVersionCode(jsonObject.get("code")+"");
        } catch (Exception e) {
            return null;
        }
        return appVersionInfo;
    }

    /**
     * 内容转string
     * @param is
     * @return
     * guonh 2020年1月9日
     */
    public static String getContent(InputStream is) {
        String result = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        try {
            isr = new InputStreamReader(is);
            reader = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            result = sb.toString();
        } catch (IOException e) {

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }


    public static void main(String[] args) {
      //  AppVersionInfo mapIpa = ReadUtil.readIpa("3c1d08aa-9bb9-48fa-b25c-568b673b91ea.apk");

        System.out.println("==============APK==================");
       // AppVersionInfo apk = ReadUtil.readApk("D://guonh-imgs/3c1d08aa-9bb9-48fa-b25c-568b673b91ea.apk");

        System.out.println("==============WGT==================");
        AppVersionInfo wgt = ReadUtil.readWgt("D://guonh-imgs/version.1.0.8.wgt");



    }


}
